<template>
  <view class="transaction-container">
    <!-- 余额信息 -->
    <view class="balance-card">
      <view class="balance-header">
        <text class="title">会员余额</text>
        <text class="subtitle">(元)</text>
      </view>
      <view class="balance-amount">
        <text>{{ balanceInfo.availableBalance }}</text>
      </view>
      <view class="balance-footer">
        <view class="balance-item">
          <text class="label">冻结金额</text>
          <text class="value">{{ balanceInfo.frozenBalance }}</text>
        </view>
        <view class="balance-item">
          <text class="label">累计收入</text>
          <text class="value">{{ balanceInfo.totalIncome }}</text>
        </view>
      </view>
    </view>
    
    <!-- 交易记录 -->
    <scroll-view 
      class="transaction-scroll" 
      scroll-y
      @scrolltolower="loadMore"
      :scroll-with-animation="true"
    >
      <view class="transaction-list">
        <view class="list-header">
          <text class="title">交易记录</text>
          <picker 
            class="date-picker" 
            mode="date" 
            fields="month" 
            :value="filterDate" 
            @change="onDateChange"
          >
            <view class="picker-content">
              <text>{{ filterDateText }}</text>
              <uni-icons type="arrowdown" size="16" color="#999"></uni-icons>
            </view>
          </picker>
        </view>
        
        <transaction-item 
          v-for="(item, index) in transactionList" 
          :key="index" 
          :transaction="item" 
        />
        
        <!-- 加载状态 -->
        <view class="load-status">
          <uni-load-more 
            :status="loadStatus" 
            :content-text="{
              contentdown: '上拉加载更多',
              contentrefresh: '加载中',
              contentnomore: '没有更多了'
            }" 
          />
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import TransactionItem from './components/TransactionItem.vue'

// 余额信息
const balanceInfo = ref({
  availableBalance: '1,256.80',
  frozenBalance: '200.00',
  totalIncome: '3,450.50'
})

// 交易记录数据
const transactionList = ref([])
const page = ref(1)
const pageSize = 20
const loadStatus = ref('more') // more / loading / noMore

// 日期筛选
const filterDate = ref('')
const filterDateText = computed(() => {
  if (!filterDate.value) return '全部时间'
  const date = new Date(filterDate.value)
  return `${date.getFullYear()}年${date.getMonth() + 1}月`
})

// 页面加载
onLoad(() => {
  // 获取当前月份作为默认筛选
  const now = new Date()
  filterDate.value = `${now.getFullYear()}-${(now.getMonth() + 1).toString().padStart(2, '0')}`
  // 获取初始数据
  fetchBalanceInfo()
  fetchTransactions()
})

// 获取余额信息
const fetchBalanceInfo = () => {
  // 模拟API请求
  console.log('获取余额信息')
}

// 获取交易记录
const fetchTransactions = () => {
  if (loadStatus.value === 'noMore') return
  
  loadStatus.value = 'loading'
  
  // 模拟API请求延迟
  setTimeout(() => {
    // 模拟数据
    const newData = generateMockTransactions(page.value, pageSize, filterDate.value)
    
    if (newData.length === 0) {
      loadStatus.value = 'noMore'
      if (page.value === 1) {
        uni.showToast({
          title: '暂无交易记录',
          icon: 'none'
        })
      }
    } else {
      transactionList.value = [...transactionList.value, ...newData]
      page.value++
      loadStatus.value = newData.length < pageSize ? 'noMore' : 'more'
    }
  }, 800)
}

// 生成模拟交易数据
const generateMockTransactions = (page, size, filterDate) => {
  if (page > 3) return [] // 模拟只有3页数据
  
  const types = ['recharge', 'payment', 'refund', 'withdraw', 'income']
  const typeNames = {
    'recharge': '充值',
    'payment': '消费',
    'refund': '退款',
    'withdraw': '提现',
    'income': '收入'
  }
  const icons = {
    'recharge': 'plus',
    'payment': 'minus',
    'refund': 'undo',
    'withdraw': 'arrow-up',
    'income': 'arrow-down'
  }
  const colors = {
    'recharge': '#4CAF50',
    'payment': '#F44336',
    'refund': '#2196F3',
    'withdraw': '#FF9800',
    'income': '#9C27B0'
  }
  
  const now = new Date()
  let baseDate = now
  if (filterDate) {
    const [year, month] = filterDate.split('-')
    baseDate = new Date(year, month - 1, 1)
  }
  
  const data = []
  for (let i = 0; i < size; i++) {
    const type = types[Math.floor(Math.random() * types.length)]
    const amount = (Math.random() * 1000).toFixed(2)
    const date = new Date(baseDate)
    date.setDate(Math.floor(Math.random() * 28) + 1)
    date.setHours(Math.floor(Math.random() * 24))
    date.setMinutes(Math.floor(Math.random() * 60))
    
    data.push({
      id: `trans_${page}_${i}`,
      type,
      typeName: typeNames[type],
      icon: icons[type],
      color: colors[type],
      amount,
      time: date.toISOString(),
      status: Math.random() > 0.2 ? 'success' : 'processing',
      remark: type === 'payment' ? '购买商品' : 
              type === 'recharge' ? '微信充值' :
              type === 'income' ? '邀请奖励' : ''
    })
  }
  
  // 按时间降序排序
  return data.sort((a, b) => new Date(b.time) - new Date(a.time))
}

// 日期筛选变化
const onDateChange = (e) => {
  filterDate.value = e.detail.value
  // 重置分页数据
  page.value = 1
  transactionList.value = []
  loadStatus.value = 'more'
  // 重新加载数据
  fetchTransactions()
}

// 加载更多
const loadMore = () => {
  fetchTransactions()
}

// 返回上一页
const goBack = () => {
  uni.navigateBack()
}
</script>

<style lang="scss" scoped>

.transaction-container {
  height: calc(100vh - 100rpx);
  display: flex;
  flex-direction: column;
  background-color: $light-bg;
}

.balance-card {
  background: linear-gradient(135deg, $primary-color, $secondary-color);
  border-radius: 16rpx;
  padding: 40rpx 30rpx;
  margin: 20rpx;
  color: $text-color-inverse;
  
  .balance-header {
    display: flex;
    align-items: flex-end;
    margin-bottom: 30rpx;
    
    .title {
      font-size: $font-size-30rpx;
      font-weight: bold;
      margin-right: 10rpx;
    }
    
    .subtitle {
      font-size: $font-size-24rpx;
      opacity: 0.8;
      padding-bottom: 2rpx;
    }
  }
  
  .balance-amount {
    font-size: 60rpx;
    font-weight: bold;
    margin-bottom: 40rpx;
  }
  
  .balance-footer {
    display: flex;
    justify-content: space-between;
    
    .balance-item {
      display: flex;
      flex-direction: column;
      
      .label {
        font-size: $font-size-24rpx;
        opacity: 0.8;
        margin-bottom: 8rpx;
      }
      
      .value {
        font-size: $font-size-28rpx;
        font-weight: bold;
      }
    }
  }
}

.transaction-scroll {
  flex: 1;
  height: calc(100vh - 500rpx);
}

.transaction-list {
  background-color: $white-bg;
  border-radius: 16rpx;
  margin: 20rpx;
  padding: 0 30rpx;
  
  .list-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx 0;
    border-bottom: 1rpx solid #f5f5f5;
    
    .title {
      font-size: $font-size-30rpx;
      font-weight: bold;
      color: $text-color;
    }
    
    .date-picker {
      .picker-content {
        display: flex;
        align-items: center;
        font-size: $font-size-26rpx;
        color: $text-color-666;
        
        text {
          margin-right: 10rpx;
        }
      }
    }
  }
}

.load-status {
  padding: 30rpx 0;
}
</style>